<template>
  <view class="back-top" :class="{ 'back-top--show': backTop || value }" :style="[getStyle]" @click="handleClick">
    <slot>
      <m-icon name="top" size="30" color="#262626" />
    </slot>
  </view>
</template>

<script lang="ts">
import { defineComponent, reactive, toRefs, computed } from '@vue/composition-api'
import { usePageScroll } from '@/hooks'

export default defineComponent({
  props: {
    value: {
      type: Boolean,
      default: false,
    },
    bottom: {
      type: Number,
      default: 200,
    },
    right: {
      type: Number,
      default: 24,
    },
    distance: {
      type: Number,
      default: 200,
    },
    zIndex: {
      type: Number,
      default: 10,
    },
    isAnimation: {
      type: Boolean,
      default: true,
    },
    duration: {
      type: Number,
      default: 200,
    },
  },
  emits: ['click'],
  setup(props, { emit, slots }) {
    const state = reactive({
      backTop: false,
      scrollTop: 0,
    })
    const handleClick = (e) => {
      if (!slots.default) {
        uni.pageScrollTo({
          scrollTop: 0,
          duration: props.isAnimation ? props.duration : 0,
        })
      }
      emit('click', e)
    }
    const getStyle = computed(() => {
      return {
        right: props.right + 'rpx',
        bottom: props.bottom + 'rpx',
      }
    })

    usePageScroll(({ scrollTop }) => {
      state.scrollTop = scrollTop

      state.backTop = scrollTop > props.distance
    })

    return {
      ...toRefs(state),
      getStyle,
      handleClick,
    }
  },
})
</script>
<style lang="scss" scoped>
.back-top {
  display: none;
  position: fixed;
  z-index: 20089;
  &--show {
    width: 80rpx;
    height: 80rpx;
    background: $--bg-content-c;
    box-shadow: 0px 4rpx 13rpx 0px rgba(144, 144, 144, 0.5);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  &--show :active {
    background: rgba(0, 0, 0, 0.1);
  }
  &-main {
    transition: all 0.2s ease-in-out;
  }
}
</style>
